package com.omri.when.there;

import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.util.TypedValue;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.Toast;

public class MainActivity extends Activity implements OnItemClickListener,
		OnClickListener, LocationListener {
	private static final String MAP_URL = ("http://maps.googleapis.com/maps/api/staticmap?");
	private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/geocode/json";
	String mpurl;
	private static final String LOG_TAG = "when.There";
	String str;
	String sFormaAddress;
	String sResultLat;
	String sResultLng;
	String positionId;
	Float resultLng = null;
	Float resultLat = null;
	private WebView webView;
	StringBuilder jsonResults;
	JSONArray resultsArray;
	private LocationManager locationManager;
	private String provider;
	Location locationGPS;
	String myLatitude;

	// private static final String API_KEY =
	// "AIzaSyDmoVvEtOHv_KR-lA2t-5cAP4uvIFNRfnQ";

	private ArrayList<String> autocomplete(String input) {
		ArrayList<String> resultList = null;

		HttpURLConnection conn = null;
		jsonResults = new StringBuilder();
		try {
			StringBuilder sb = new StringBuilder(PLACES_API_BASE);
			sb.append("?address=" + URLEncoder.encode(input, "utf8")
					+ "&sensor=false");
			Log.d("URL", sb.toString());

			URL url = new URL(sb.toString());
			conn = (HttpURLConnection) url.openConnection();
			InputStreamReader in = new InputStreamReader(conn.getInputStream());

			// Load the results into a StringBuilder
			int read;
			char[] buff = new char[1024];
			while ((read = in.read(buff)) != -1) {
				jsonResults.append(buff, 0, read);
			}
		} catch (MalformedURLException e) {
			Log.e(LOG_TAG, "Error processing Places API URL", e);
			return resultList;
		} catch (IOException e) {
			Log.e(LOG_TAG, "Error connecting to Places API", e);
			return resultList;
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
		}
		try {
			JSONObject jsonObject = new JSONObject(jsonResults.toString());
			resultList = new ArrayList<String>(jsonObject.length());
			resultsArray = jsonObject.getJSONArray("results");
			// Get the formatted addresses
			for (int i = 0; i < jsonObject.length(); i++) {
				JSONObject fAddress = resultsArray.getJSONObject(i);
				resultList.add(sFormaAddress = fAddress
						.getString("formatted_address"));
			}
			Log.d("Choosen location: ", str);
		} catch (JSONException e) {
			Log.e(LOG_TAG, "Cannot process JSON results", e);
		}
		return resultList;

	}

	class PlacesAutoCompleteAdapter extends ArrayAdapter<String> implements
			Filterable {

		private ArrayList<String> resultList;

		public PlacesAutoCompleteAdapter(Context context, int textViewResourceId) {
			super(context, textViewResourceId);
		}

		@Override
		public int getCount() {
			return resultList.size();
		}

		@Override
		public String getItem(int index) {
			return resultList.get(index);
		}

		@Override
		public Filter getFilter() {
			Filter filter = new Filter() {
				@Override
				protected FilterResults performFiltering(CharSequence constraint) {
					FilterResults filterResults = new FilterResults();
					if (constraint != null) {
						// Retrieve the autocomplete results.
						resultList = autocomplete(constraint.toString());

						// Assign the data to the FilterResults
						filterResults.values = resultList;
						filterResults.count = resultList.size();
					}
					return filterResults;
				}

				@Override
				protected void publishResults(CharSequence constraint,
						FilterResults results) {
					if (results != null && results.count > 0) {
						notifyDataSetChanged();
					} else {
						notifyDataSetInvalidated();
					}
				}
			};
			return filter;
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		Button bNext1 = (Button) findViewById(R.id.bNext1);
		Button bMenuButton = (Button) findViewById(R.id.bMenuButton);
		AutoCompleteTextView autoCompView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
		autoCompView.setAdapter(new PlacesAutoCompleteAdapter(this,
				R.layout.list_item));
		getFirstLocation();
		setupWebView();
		autoCompView.setThreshold(2);
		autoCompView.setOnItemClickListener(this);
		bNext1.setOnClickListener(this);
		bMenuButton.setOnClickListener(this);
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub

	}

	private void getFirstLocation() {
		// Get the location manager
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		// Define the criteria how to select the locatioin provider -> use
		// default
		Criteria criteria = new Criteria();
		provider = locationManager.getBestProvider(criteria, true);
		locationGPS = locationManager.getLastKnownLocation(provider);
		// Initialize the location fields
		if (locationGPS != null) {
			resultLat = (float) locationGPS.getLatitude();
			resultLng = (float) locationGPS.getLongitude();
		} else {
			resultLat = null;
			resultLng = null;
		}
	}

	/* Request updates at startup */
	@Override
	protected void onResume() {
		super.onResume();
		locationManager.requestLocationUpdates(provider, 400, 1, this);
	}

	/* Remove the locationlistener updates when Activity is paused */
	@Override
	protected void onPause() {
		super.onPause();
		locationManager.removeUpdates(this);
	}

	public void setupWebView() {
		StringBuilder mapUrl = new StringBuilder(MAP_URL);
		mapUrl.append("&zoom=16&size=300x250&maptype=roadmap&markers=color:blue%7Clabel:%7C");
		mapUrl.append(resultLat + "," + resultLng);
		mapUrl.append("&sensor=false");
		mpurl = mapUrl.toString();
		Log.d("map URL", mpurl);
		webView = (WebView) findViewById(R.id.webview);
		// Wait for the page to load then send the location information
		webView.setWebViewClient(new WebViewClient());
		webView.loadUrl(mpurl);
		Log.d("map URL", mpurl);
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view,
			int position, long id) {
		str = (String) adapterView.getItemAtPosition(position);
		Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
		positionId = ("" + position);
		location();
		setupWebView();
	}

	public void location() {
		JSONObject geometryLocation;
		try {
			geometryLocation = resultsArray.getJSONObject(Integer
					.parseInt(positionId));
			JSONObject geometryObject = geometryLocation
					.getJSONObject("geometry");
			JSONObject locationObject = geometryObject
					.getJSONObject("location");
			sResultLat = locationObject.getString("lat");
			sResultLng = locationObject.getString("lng");
			resultLng = Float.parseFloat(sResultLng);
			resultLat = Float.parseFloat(sResultLat);

		} catch (NumberFormatException e) {
			// Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// Auto-generated catch block
			e.printStackTrace();
		}

	}

	@Override
	public void onClick(View v) {
		// Pressing next will move to next screen
		switch (v.getId()) {
		case (R.id.bNext1):
			Bundle basket = new Bundle();
			basket.putString("address", str);
			basket.putString("latitude", sResultLat);
			basket.putString("longitude", sResultLng);
			Intent a = new Intent(MainActivity.this, Second.class);
			a.putExtras(basket);
			startActivity(a);
			break;
		case (R.id.bMenuButton):
			int width = (int) TypedValue.applyDimension(
					TypedValue.COMPLEX_UNIT_DIP, 40, getResources()
							.getDisplayMetrics());
			SlideoutActivity.prepare(MainActivity.this, R.id.inner_content,
					width);
			startActivity(new Intent(MainActivity.this, MenuActivity.class));
			overridePendingTransition(0, 0);
			break;
		}
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		Toast.makeText(this, "For better map enable your location " + provider,
				Toast.LENGTH_SHORT).show();
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		Toast.makeText(this, "Enabled new provider " + provider,
				Toast.LENGTH_SHORT).show();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == android.R.id.home) {
			int width = (int) TypedValue.applyDimension(
					TypedValue.COMPLEX_UNIT_DIP, 40, getResources()
							.getDisplayMetrics());
			SlideoutActivity.prepare(MainActivity.this, R.id.inner_content,
					width);
			startActivity(new Intent(MainActivity.this, MenuActivity.class));
			overridePendingTransition(0, 0);
		}
		return true;
	}

}